package org.mte.sak.sort.comparator.impl;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

import org.mte.sak.sort.comparator.AbstractComparator;

/**
 * <i>Comparatore Double</i>.
 *
 * @author Marco Traversari
 * @version $Revision: 1.2 $ $Date: 2011-12-27 11:42:33 $
 *
 */
public class DoubleComparator extends AbstractComparator  {

    /**
     * DoubleComparator
     */
	public DoubleComparator() {
	}

    /**
     * DoubleComparator
     * @param isAscending
     */
	public DoubleComparator(boolean isAscending) {
		this.isAscending = isAscending;
	}

    /**
     * getValue
     * @param value
     * @param formatReference
     * @return il valore dell'oggetto.
     * @see org.dromedary.lib.sort.Comparator#getValue(java.lang.String, java.lang.Object)
     */
	public Object getValue(String value, Object formatReference) {
		Locale locale = (Locale) formatReference;
		NumberFormat numberFormat = NumberFormat.getInstance(locale);
		Number number = null;
		Double doubleNumber = null;
		if (value != null && !value.equals("")) {
			try {
				number = numberFormat.parse(value);
				doubleNumber = new Double(number.doubleValue());
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}  else {
			doubleNumber = new Double(Double.MAX_VALUE);
		}
		return doubleNumber;
	}
	
	/**
	 * getValue
	 * @param value
	 * @param formatReference
	 * @param locale
	 * @return value
	 */
	public Object getValue(String value, Object formatReference, Locale locale) {
		return getValue(value, formatReference);
	}

    /**
     * compare
     * @param obj1
     * @param obj2
     * @return true, false.
     * @see org.dromedary.lib.sort.Comparator#compare(java.lang.Object, java.lang.Object)
     */
	public boolean compare(Object obj1, Object obj2) {
		boolean result = isAscending;
		if (compareOneToOne(obj1, obj2) > 0) {
			result = !isAscending;
		}
		return result;
	}

    /**
     * compareOneToOne
     * @param obj1
     * @param obj2
     * @return true, false.
     * @see org.dromedary.lib.sort.Comparator#compareOneToOne(java.lang.Object, java.lang.Object)
     */
	public int compareOneToOne(Object obj1, Object obj2) {
		Double double1 = (Double) obj1;
		Double double2 = (Double) obj2;
		return double1.compareTo(double2);
	}
}